﻿@using WishlistUtilities;
@using System.Collections;
@{
	PageData["Title"] = "User Management";

	WebSecurity.RequireAuthenticatedUser();
    if (!Roles.IsUserInRole("admin")) {
    	Response.Redirect("~");
    }

	var db = Database.Open("wishlistdb");
    var query = db.Query("SELECT * FROM WishlistUser");

	WebGrid usersGrid = new WebGrid(query, rowsPerPage: 3, defaultSort: "Username");
}

<h1>User Account Management</h1>
<script type="text/javascript">
	function deleteUser(userId) {
		$("#DeleteConfirmationDialog" + userId).dialog(
			{
				resizable: false, height: 250, width: 300, modal: true, closeOnEscape: true, draggable: false,
				buttons: {
					'Cancel': function() {
						$(this).dialog("close");
					 },
					'OK': function() {
						document.forms['deleteUserForm'+userId].submit();
					}
				}
			}
		);
	}
</script>
@{
// POST of the whole page
    var errorMessage = "";    
	if (IsPost) {
        if (Request["action"].IsEmpty()) {
			Response.Redirect("~/Shared/Errors/Errors/Error");
		}
       
        //If action is to delete a user, ensure you are not deleting yourself and then remove the user
		if (Request["action"] == "Delete") {
			var userToDelete = Request["delete_id"];
			if (userToDelete.IsInt()) {
				if (userToDelete.AsInt() != WebSecurity.CurrentUserId) {
					try {
                        //Delete account
                        var username = db.QuerySingle("SELECT Username FROM WishlistUser WHERE Id=@0", userToDelete).Username;
                        ((ExtendedMembershipProvider)(Membership.Provider)).DeleteAccount(username);
                        //Deletes cascade so we don't need to handle deleting the user's lists explicitly
                        db.Execute("DELETE FROM WishlistUser WHERE Id=@0", userToDelete);
					} catch (Exception) {
                        Response.Redirect("~/Shared/Errors/Error");
					}
                    usersGrid = new WebGrid(db.Query("SELECT * FROM WishlistUser"), rowsPerPage: 3, defaultSort: "Username", ajaxUpdateContainerId: "ajaxDiv");
				} else {
					//User will only see this error if they've injected data into the request attempting to delete themselves
					errorMessage = "<li>You can't delete yourself!</li>";
				}
			} else {
				Response.Redirect("~/Shared/Errors/Error");
			}
            
        //If JS is disabled and user would like to perform a selection
        } else if (Request["action"] == "Select") {
            Response.Redirect(Request["selectUrl"]);
        }
        
        // Role Actions
        //Create Role action
        else if (Request["action"] == "RoleCreate") {
            var roleToCreate = Request["createRole_name"];
            if ((roleToCreate!=null) && (roleToCreate!="")) {
                if (!(Roles.RoleExists(roleToCreate))) {
                    try {
                       Roles.CreateRole(roleToCreate); 
                    } catch(Exception) {
                        Response.Redirect("~/Shared/Errors/Error");
                    }
                }            
            }
        }
        
        // Delete Role action 
        else if (Request["action"] == "RoleDelete") {            
			var roleToDelete = Request["deleteRole_Rolename"];
            if (roleToDelete != "admin") {
                try {                
                    Roles.DeleteRole(roleToDelete, false);
                } catch (Exception) {
                    Response.Redirect("~/Shared/Errors/Error");
                }
            }
       }        
    }
    if (!errorMessage.IsEmpty()) {
        @RenderPage("~/Shared/Errors/_FormInputError.cshtml", errorMessage);
    }
}

<div id="userList">
    @usersGrid.GetHtml(
        selectedRowStyle: "selected",
	    mode: WebGridPagerModes.All,
	    previousText: "Previous", 
	    nextText: "Next",
	    columns: usersGrid.Columns(
		    usersGrid.Column(header: "Gravatar", format: @: @Gravatar.GetHtml(item.Email, imageSize:40, rating: GravatarRating.PG)
            ),
		    usersGrid.Column("Username", "Username"),
		    usersGrid.Column("FirstName", "First Name"),
		    usersGrid.Column("LastName", "Last Name"),
		    usersGrid.Column("Email", "E-mail"),
		    usersGrid.Column(header: "Administrator", format: 
			    @: @if (Roles.IsUserInRole(item.Username, "admin")) { <text>Yes</text> } else { <text>No</text> }
		    ),
            usersGrid.Column(header: "Confirmed?", format:
                @: @if (WebSecurity.IsConfirmed(item.UserName)) { <text>Yes</text> } else { <text>No</text> }
            ),
            usersGrid.Column(header: "Edit User?",format: 
                @<text>                    
                    <a href="@Href("~/Admin/EditUser/"+item.Username)">Edit User</a>
                </text>
            ),
		    usersGrid.Column(header: "Delete User?", format:
			    @<text>
			    @if (item.Id != WebSecurity.CurrentUserId) {
				    <span>
					    <input type="button" onclick="javascript:deleteUser(@(item.Id))" value="Delete"/>
					    <form id="deleteUserForm@(item.Id)" method="post" action="">
						    <input name="delete_id" type="hidden" value="@item.Id" />
						    <input name="action" type="hidden" value="Delete"/>
					    </form>
					    <div id="DeleteConfirmationDialog@(item.Id)" class="jquery-dialog" title="Delete List">
						    <span class="ui-icon ui-icon-alert ui-icon-float"></span>
						    <p>Are you sure you want to delete @item.Username?</p>
					    </div>
				    </span>
			    } else {
				    <span class="info">This is you</span>
			    }
			    </text>
		    )
	    )
    )
    </div>
<p>
    <a href="@Href("~/Admin/CreateUser")">Create User</a>
</p>
<!-- Roles -->
@{
    var queryRoles = db.Query("SELECT RoleId, RoleName as Rolename FROM webpages_Roles");

	WebGrid rolesGrid = new WebGrid(queryRoles, rowsPerPage: 10, defaultSort: "Rolename");
}
<h1>Role Management</h1>
<script type="text/javascript">
	function deleteRole(roleId) {
		$("#DeleteConfirmationDialog" + roleId).dialog(
			{
				resizable: false, height: 250, width: 300, modal: true, closeOnEscape: true, draggable: false,
				buttons: {
					'Cancel': function() {
						$(this).dialog("close");
					 },
					'OK': function() {
						document.forms['deleteRoleForm'+roleId].submit();
					}
				}
			}
		);
	}
    function createRole(roleName) {
		$("#CreateConfirmationDialog").dialog(
			{
				resizable: false, height: 250, width: 300, modal: true, closeOnEscape: true, draggable: false,
				buttons: {
					'Cancel': function() {
						$(this).dialog("close");
					 },
					'OK': function() {
						document.forms['createRoleForm'].submit();
					}
				}
			}
		);
	}
</script>
<div id="roleList">
    @rolesGrid.GetHtml(        
	    mode: WebGridPagerModes.All,
	    previousText: "Previous", 
	    nextText: "Next",
	    columns: rolesGrid.Columns(		    
		    rolesGrid.Column(header: "Role Name", style: "roleName", format:
                @<text>                    
                    <a href="@Href("~/Admin/RoleDetails/"+item.Rolename)">@(item.Rolename)</a>
                </text>),
                rolesGrid.Column(header: "SKU", style: "skuLink", format: @: @Freemium.GetStockKeepingUnitLinkHtml(item.Rolename)
                        ),                           
		        rolesGrid.Column(header: "Delete Role?", format:
			    @<text>
                    @if (item.Rolename == "admin") {
                        <span class="info">Cannot delete</span>
                    } else {
				    <span>                            
					    <input type="button" onclick="javascript:deleteRole('@(item.RoleId)')" value="Delete"/>                        
					    <form id="deleteRoleForm@(item.RoleId)" method="post" action="">
						    <input name="deleteRole_Rolename" type="hidden" value="@item.Rolename" />
						    <input name="action" type="hidden" value="RoleDelete"/>
					    </form>
					    <div id="DeleteConfirmationDialog@(item.RoleId)" class="jquery-dialog" title="Delete Role">
						    <span class="ui-icon ui-icon-alert ui-icon-float"></span>
						    <p>Are you sure you want to delete @item.Rolename ?</p>
					    </div>
				    </span>	
                    }
			    </text>
		    )
	    )
    )
</div>
<br/>
<div>
    <form id="createRoleForm" method="post" action="">
        <label>Role:</label>
        <input name="createRole_name" type="text" />
        <input name="action" type="hidden" value="RoleCreate"/>
        <input name="submitRole" type="submit" value="Create Role" />
    </form>
    <a href="@Href("~/Freemium/Admin")">Freemium Admin</a>
</div>